package com.wshl.aijiuunion;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadFailedListener;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.controller.fragment.HomeFragment;
import com.wshl.aijiuunion.controller.fragment.MineFragment;
import com.wshl.aijiuunion.controller.fragment.ShopFragment;
import com.wshl.aijiuunion.controller.fragment.TabFragment;
import com.wshl.aijiuunion.controller.fragment.VideoFragment;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.MyFragmentTabHost;
import com.wshl.aijiuunion.view.bean.CheckVersionBean;
import com.wshl.aijiuunion.view.bean.EventBeans;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created buy 风凊扬 on 2019/10/23 0023
 */
public class HomeActivity extends AppCompatActivity {

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.tabHost)
    MyFragmentTabHost tabHost;


    private String currentTab = "首页";


    //正常四个按钮的写法
    private String[] tabs = new String[]{"首页", "商城", "视频培训", "我的"};
    //  private String[] tabs = new String[]{"首页", "商城", "我的"};
    private Class[] mFragmentClasses = new Class[]{HomeFragment.class, ShopFragment.class,
            VideoFragment.class, MineFragment.class};
    //    private Class[] mFragmentClasses = new Class[]{HomeFragment.class, ShopFragment.class,
//            MineFragment.class};
    private int[] selectorImg = new int[]{R.drawable.bottom_home_selector, R.drawable.bottom_shop_selector,
            R.drawable.bottom_video_selector, R.drawable.bottom_mine_selector};
    //    private int[] selectorImg = new int[]{R.drawable.bottom_home_selector, R.drawable.bottom_shop_selector,
//            R.drawable.bottom_mine_selector};
    private RequestModel model;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        int isShowVideo = SPUtils.getInstance().getInt(GlobConstant.ISSHOWVIDEO, 0);

        model = new RequestModel();
        // 初始化tabHost
        tabHost.setup(this, getSupportFragmentManager(), R.id.fl_content);
        tabHost.getTabWidget().setShowDividers(0);//去掉分割线
        for (int i = 0; i < tabs.length; i++) {
            if (isShowVideo == 0) {
                if (i != 2) {
                    tabHost.addTab(tabHost.newTabSpec(tabs[i]).setIndicator(getTabView(i)), mFragmentClasses[i], null);
                }

            } else if (isShowVideo == 1) {
                tabHost.addTab(tabHost.newTabSpec(tabs[i]).setIndicator(getTabView(i)), mFragmentClasses[i], null);

            }
        }
        // 设置默认tab
        //切换tab时的监听
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                currentTab = tabId;
            }
        });

        checkVersion();

    }

    /**
     * tab的view对象
     *
     * @param index 索引
     * @return view对象
     */
    private View getTabView(int index) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.tab_indicator, null);
        TextView tv_indicator = (TextView) inflate.findViewById(R.id.tv_indicator);

        //正常写法
        Drawable drawable = getApplicationContext().getResources().getDrawable(selectorImg[index]);
        tv_indicator.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        tv_indicator.setText(tabs[index]);
        return inflate;
    }


    private long mExitTime;// 上一次点击返回键的时间

    // 重写onKeyDown方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {  // 是返回键

            LogUtils.e(currentTab);
            if (currentTab.equals("首页")) {

                //如果当前显示的fragment是首页
                // 点击两次返回键退出程序
                if (System.currentTimeMillis() - mExitTime > 2000) {
                    // 如果当前点击返回键的时间减去上一次点击返回键的时间大于2秒
                    ToastUtils.showShort("再按一次退出");
                    // 重新赋值,方便下次使用
                    mExitTime = System.currentTimeMillis();
                } else {
                    // 如果小于两秒,就直接退出程序
                    SPUtils.getInstance().put(GlobConstant.ISSTARTMIAN, true);
                    finish();

                }
            } else {
                //如果当前不是首页,先切换到首页
                tabHost.setCurrentTab(0);
            }


            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void closectivity(EventBeans eventString) {
        //当接收到关闭页面的广播后
        if (eventString.getCode().equals(GlobConstant.FINISHACLLACTIVITY)) {
            LogUtils.i("关闭所有页面");
            this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void checkVersion() {

        String appVersionName = AppUtils.getAppVersionName();
        model.checkVersion(HomeActivity.this, appVersionName, false, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                CheckVersionBean checkVersionBean = GsonUtils.fromJson(response, CheckVersionBean.class);
                CheckVersionBean.DataBean data = checkVersionBean.getData();
                String url = data.getUrl();
                String version = data.getVersion();
                String content = data.getContent();
                downLoadApk(url, "发现新版本:" + version + "\n" + content);
            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }

    private void downLoadApk(String url, final String content) {
        DownloadBuilder downloadBuilder = AllenVersionChecker
                .getInstance()
                .downloadOnly(
                        UIData.create().setDownloadUrl(url)
                );

        downloadBuilder.setForceRedownload(true);
        downloadBuilder.setCustomVersionDialogListener(new CustomVersionDialogListener() {
            @Override
            public Dialog getCustomVersionDialog(Context context, UIData versionBundle) {


                View view1 = LayoutInflater.from(HomeActivity.this).inflate(R.layout.dialog_update, null);
                final Dialog dialog = new Dialog(context, R.style.myDialog);
                TextView tvContent = view1.findViewById(R.id.tv_versioncontent);
                tvContent.setText(content);
                dialog.setContentView(view1);
                dialog.setCancelable(false);
                return dialog;


            }
        });

        //设置这个监听,表示要强制更新,下载时的dialog不能被取消
        downloadBuilder.setForceUpdateListener(new ForceUpdateListener() {
            @Override
            public void onShouldForceUpdate() {


            }
        });


        downloadBuilder.setShowDownloadingDialog(true);//是否显示下载进度对话框
        downloadBuilder.setCustomDownloadingDialogListener(new CustomDownloadingDialogListener() {
            @Override
            public Dialog getCustomDownloadingDialog(Context context, int progress, UIData versionBundle) {


                Dialog baseDialog = new Dialog(context, R.style.myDialog);
                View view = LayoutInflater.from(HomeActivity.this).inflate(R.layout.dialog_download, null);
                baseDialog.setContentView(view);
                baseDialog.setCancelable(false);
                return baseDialog;
            }

            //下载中会不断回调updateUI方法
            @Override
            public void updateUI(Dialog dialog, int progress, UIData versionBundle) {
                TextView tvProgress = dialog.findViewById(R.id.tv_download_progress);
                ProgressBar progressBar = dialog.findViewById(R.id.progressBar);
                progressBar.setProgress(progress);
                tvProgress.setText(getString(R.string.versionchecklib_progress, progress));
            }
        });

        downloadBuilder.setCustomDownloadFailedListener(new CustomDownloadFailedListener() {
            @Override
            public Dialog getCustomDownloadFailed(Context context, UIData versionBundle) {

                Dialog baseDialog = new Dialog(context, R.style.myDialog);
                View view = LayoutInflater.from(HomeActivity.this).inflate(R.layout.dialog_faild, null);
                baseDialog.setContentView(view);
                //   baseDialog.setCancelable(false);
                return baseDialog;

            }
        });
        downloadBuilder.executeMission(HomeActivity.this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 103) {

            if (resultCode == RESULT_OK) {

                if (data != null) {

                    int type = data.getIntExtra("type", 0);
                    int cateid = data.getIntExtra("cateid", 0);
                    EventBus.getDefault().post(new EventBeans(GlobConstant.VIDEOSELECT, type, cateid));
                }

            }

        }
    }
}
